
/****************************************************************************/
/*Copyright (c) 2011, Florent DEVILLE.                                      */
/*All rights reserved.                                                      */
/*                                                                          */
/*Redistribution and use in source and binary forms, with or without        */
/*modification, are permitted provided that the following conditions        */
/*are met:                                                                  */
/*                                                                          */
/* - Redistributions of source code must retain the above copyright         */
/*notice, this list of conditions and the following disclaimer.             */
/* - Redistributions in binary form must reproduce the above                */
/*copyright notice, this list of conditions and the following               */
/*disclaimer in the documentation and/or other materials provided           */
/*with the distribution.                                                    */
/* - The names of its contributors cannot be used to endorse or promote     */
/*products derived from this software without specific prior written        */
/*permission.                                                               */
/* - The source code cannot be used for commercial purposes without         */ 
/*its contributors' permission.                                             */
/*                                                                          */
/*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         */
/*LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         */
/*FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            */
/*COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       */
/*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,      */
/*BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;          */
/*LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER          */
/*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT        */
/*LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN         */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/*POSSIBILITY OF SUCH DAMAGE.                                               */
/****************************************************************************/

#include "RTTexture.h"
#include "RTMatrix33.h"

namespace RT
{

	RTTexture::RTTexture() : _picture(0)
	{
		_textureName = "";
	}

	RTTexture::~RTTexture()
	{
		if (_picture != 0)
		{
			SDL_FreeSurface(_picture);
			_picture = 0;
		}
	}

	bool RTTexture::loadTexture(const string& filename)
	{
		_textureName = filename;

		//load the picture
		_picture=IMG_Load(_textureName.c_str());
		if(_picture == 0)
			return false;

		//lock the surface
		SDL_LockSurface(_picture);

		//picture width
		_width = _picture->w - 1;

		//picture height
		_height = _picture->h - 1;

		//picture bytes per pixel
		_bytesPerPixel = _picture->format->BitsPerPixel / 8;

		return true;
	}

	//return the color of the pixel for the poI32 p in the triangle t.
	//Solver using cramer's rule
	RTColor RTTexture::getColor(const RTVector3f& p, RTPrimTriangle* const t)const
	{
		//store the current poI32
		RTVector3f pT = p;

		//get the vertices
		RTVector3f* vertex = t->getVertices();

		if(t->_useTranslation)
		{
			pT = p + t->_offset;
			vertex = t->_uvTranslated;
		}

		//calculate D
		RTMatrix33 mD(vertex[0], vertex[1], vertex[2]); 
		F32 D = mD.det();

		//calculate A1
		RTMatrix33 mA1(pT, vertex[1], vertex[2]);
		F32 A1 = mA1.det();

		//calculate A2
		RTMatrix33 mA2(vertex[0], pT, vertex[2]);
		F32 A2 = mA2.det();

		//calculate barycentric coordinates
		F32 x = A1 / D;
		F32 y = A2 / D;
		F32 z = 1 - x - y;

		//get the uvmap
		RTVector3f* uv = t->getUV();

		//calculate uv map of p
		F32 up = uv[0].x*x + uv[1].x*y + uv[2].x*z;
		F32 vp = uv[0].y*x + uv[1].y*y + uv[2].y*z;

		//calculate the pixels coordinate
		I32 offsetX = I32(up * _width);
		I32 offsetY = I32(vp * _height);

		//saturate the pixel coordinate inside the texture (allow tiles)
		if(offsetX >= (I32)_width || offsetX < 0) offsetX %= _width;
		if(offsetY >= (I32)_height || offsetY < 0) offsetY %= _height;

		//calculate the position in the array of pixels
		U32 offset = offsetY * _picture->pitch + offsetX * _bytesPerPixel;

		//get the pixel color
		unsigned char* pixels = (unsigned char*)_picture->pixels;

		F32 R = (F32)pixels[offset] / 255;
		F32 G = (F32)pixels[offset+1] / 255;
		F32 B = (F32)pixels[offset+2] / 255;

		return RTColor(R, G, B, 1);
	}

}
